package com.example.cardgame.utils

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.RecyclerView
import com.example.cardgame.R
import com.example.cardgame.model.CardGame

class CardAdapter<T:CardGame>(val game: T):RecyclerView.Adapter<CardAdapter.CardViewHolder>() {
    class CardViewHolder(itemView: View):RecyclerView.ViewHolder(itemView) {
        val cardButton: Button
        init{
            cardButton = itemView.findViewById(R.id.button)
        }
    }

    var mListener: ((Int) -> Unit)? = null
    fun setOnClickListener(listener: (Int) -> Unit) {
        mListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
        return CardViewHolder(view)
    }

    override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
       val card = game.cards[position]
       holder.cardButton.isEnabled = !card.isMatched
        if (card.isChosen){
            holder.cardButton.text = card.toString()
            holder.cardButton.setBackgroundColor(Color.GRAY)
        } else {
            holder.cardButton.text = ""
            holder.cardButton.setBackgroundResource(R.drawable.cover)
        }
        holder.cardButton.setOnClickListener {
            mListener?.invoke(position)
        }
    }

    override fun getItemCount(): Int {
        return game.cards.size
    }
}